package com.biyao.controller.config.interceptor;


import com.biyao.schedulingcommon.exeception.UnauthorizedException;
import com.biyao.schedulingcommon.response.StatusCode;
import com.biyao.schedulingentity.oauth.TOauthAccessTokenEntity;
import com.biyao.controller.config.Constants;
import com.biyao.controller.config.api.SwaggerConfig;
import com.biyao.service.model.oauth.OauthService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 权限校验
 *
 * @author song
 */
@Component
public class OauthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private OauthService oauthService;


    @Autowired
    private SwaggerConfig swaggerConfig;

    Logger logger = LoggerFactory.getLogger(OauthInterceptor.class);


    private static final String LOGIN_URL = "/login";

    /**
     * This implementation always returns {@code true}.
     *
     * @param request
     * @param response
     * @param handler
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer url = request.getRequestURL();

        /*某些接口不需token验证,在这里配置*/
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "86400");
        response.setHeader("Access-Control-Allow-Headers", "*");

        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }

        if (url.indexOf(LOGIN_URL) >= 0
                || swaggerConfig.isSwagger(String.valueOf(url))) {
            return super.preHandle(request, response, handler);
        }

        String headToken = request.getHeader("Authorization");
        request.setCharacterEncoding("utf-8");
        if (StringUtils.isNotBlank(headToken)) {
            String accessToken = headToken.substring("Bearer".length());
            if (StringUtils.isBlank(accessToken)) {
                throw new UnauthorizedException(StatusCode.UNAUTHORIZED.getMsg());
            }
            TOauthAccessTokenEntity token = oauthService.getTokenByAccessTokenAndScope(accessToken);

            if (token == null) {
                throw new UnauthorizedException(StatusCode.UNAUTHORIZED.getMsg());
            }
            request.setAttribute(Constants.LOGIN_USER_KEY, token.getResourceOwnerId());
            return super.preHandle(request, response, handler);
        } else {
            throw new UnauthorizedException(StatusCode.UNAUTHORIZED.getMsg());
        }
    }




}
